package com.sijiao.stock.service.impl;

import com.sijiao.stock.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StockBizServiceImpl implements IStockBizService {

    private IStockService stockService;
    private IStockCacheService stockCacheService;
    private IMQProducerService mqProducerService;
    private IStockFlowService stockFlowService;

    public StockBizServiceImpl(IStockService stockService, IStockCacheService stockCacheService,
                               IMQProducerService mqProducerService, IStockFlowService stockFlowService) {
        this.stockService = stockService;
        this.stockCacheService = stockCacheService;
        this.mqProducerService = mqProducerService;
        this.stockFlowService = stockFlowService;
    }

    /**
     * 后台管理接口主动操作库存变更
     * @param skuId
     * @param stock
     * @param stockOffset
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeStock(Long skuId, Long stock, Long stockOffset) {
        boolean result = stockService.changeStock(skuId, stock, stockOffset);
        stockFlowService.manageStockOperation(skuId, stockOffset);
        // 缓存中的数据如果是库存增加或者回滚，需要基于流水表（操作类型）订阅主题
        return result;
    }

    /**
     * 申请扣减库存
     * @param orderId
     * @param skuId
     * @param stock
     * @return
     */
    @Override
    public boolean consumeStock(Long orderId, Long skuId, Long stock) {
        // 1.先发扣减消息
        // 添加业务降级处理 （保证主流程）
        mqProducerService.sendConsumeStock(orderId, skuId, stock);
        // 2.扣减缓存
        boolean success = true;
        try {
            success = stockCacheService.consumeStock(skuId, stock);
        } catch (Exception e) {
            success = false;
        }
        // 扣减失败或者请求异常，都回滚库存
        if (!success) {
            mqProducerService.rollbackStock(orderId, skuId, stock);
            return false;
        }
        return true;
    }
}
